package fr.uvsq.isty.bdh.hchess.gui.menu;

import fr.uvsq.isty.bdh.hchess.engine.GameData;
import fr.uvsq.isty.bdh.hchess.engine.GameState;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

/**
 *
 * @author Florent Hemmi <florent.hemmi@gmail.com>
 */
public class SaveItemMenu extends JMenuItem implements Observer {
    
    private GameData gameData;
    private JFileChooser fileChooser;
    
    public SaveItemMenu(GameData gameData) {
        this.gameData = gameData;
        this.fileChooser = new JFileChooser();
        
        this.setText("Save ");
        this.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
        this.setEnabled(false);
        
        this.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int returnVal = fileChooser.showSaveDialog(SaveItemMenu.this);
 
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    try {
                        SaveItemMenu.this.gameData.saveCurrentPlayingToPGN(new FileOutputStream(file));
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "Cannot save the game.", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    // Cancel by user.
                }
            }
        });
    }

    public void update(Observable o, Object arg) {
        if (gameData.getCurrentGameState() == GameState.IN_GAME)
            this.setEnabled(true);
        else
            this.setEnabled(false);
    }
}
